<?php
/**
 * Created by <xinxin.deng>.
 * Author: xinxin.deng
 * Date: 2018/9/28 13:38
 */
/**
 * 定时器获取ftp的单片源注入媒资
 * pan.liang
 */
header("Content-type: text/html; charset=utf-8");
ini_set('display_errors', 1);
set_time_limit(0);
include_once dirname(dirname(__FILE__)) . '/mgtv_v2/mgtv_init.php';
include_once dirname(dirname(__FILE__)) . '/api_v2/nn_const.php';
include_once dirname(dirname(__FILE__)) . '/api_v2/common.php';
include_once dirname(dirname(__FILE__)) . '/nn_logic/nl_common.func.php';
include_once dirname(dirname(__FILE__)).'/nn_class/ftp/ftp.class.php';
include_once dirname(dirname(__FILE__)) . '/api_v2/nn_const.php';
include_once dirname(dirname(__FILE__)) . '/api_v2/common.php';
include_once dirname(dirname(__FILE__)) . '/nn_logic/nl_log_v2.func.php';
include_once dirname(dirname(__FILE__)) . '/nn_logic/cp/cp.class.php';
include_once dirname(dirname(__FILE__)) . '/nn_class/encrypt/encrypt_aes.class.php';
class timer_execute extends nn_timer
{
    public $str_date = null;
    public $str_date_time = null;
    public $arr_full_assets_site = array();
    public $arr_media_list = null;
    public $media_cp_id = null;

    /**
     * 定时器初始化
     * @see nn_timer::action()
     */
    public function action($params = null)
    {
        $this->msg('开始执行...');
        $this->init($params);
        $this->msg('执行结束...');
    }

    /**
     * 初始化
     */
    public function init($params=null)
    {
        include_once dirname(dirname(__FILE__)) . '/nn_logic/full_assets/full_assets.class.php';
        include_once dirname(dirname(__FILE__)) . '/nn_logic/full_assets/full_assets_site.class.php';
        //include_once dirname(dirname(__FILE__)) . '/api_v2/control/standard/sync_source.php';
        $this->msg("[redis池中返回数据为:]".var_export($params, true));
        $str_third_playbill_pool = $params["bk_queue_value"];
        if(strlen($str_third_playbill_pool) <1 || $str_third_playbill_pool !='placeholder')
        {
            $this->msg("[redis节目单池中返回数据为空]".$str_third_playbill_pool);
            return ;
        }
        $cp_id = $this->arr_params['bk_queue_config']['nns_ext_info']['cp_id'];
        $media_tag = $this->arr_params['bk_queue_config']['nns_ext_info']['media_tag'];
        $ftp_url = $this->arr_params['bk_queue_config']['nns_ext_info']['ftp_url'];
        $bitrate = $this->arr_params['bk_queue_config']['nns_ext_info']['bitrate'];
        $bitrate = (int)$bitrate >0 ? (int)$bitrate : 0;
        $arr_ftp = parse_url($ftp_url);
        if(!isset($arr_ftp['scheme']) || strtolower($arr_ftp['scheme']) != 'ftp')
        {
            $this->msg("[非正常FTP地址]".$ftp_url);
            return ;
        }
        $host = isset($arr_ftp['host']) ? $arr_ftp['host'] : '';
        $port = isset($arr_ftp['port']) ? $arr_ftp['port'] : 21;
        $user = isset($arr_ftp['user']) ? $arr_ftp['user'] : '';
        $pass = isset($arr_ftp['pass']) ? $arr_ftp['pass'] : '';
        $path = isset($arr_ftp['path']) ? $arr_ftp['path'] : '/';
        if(strlen($host) <1)
        {
            $this->msg("[FTP地址为空]".$ftp_url);
            return ;
        }
        if(strlen($port) <1)
        {
            $this->msg("[FTP端口为空]".$ftp_url);
            return ;
        }
        if(strlen($user) <1)
        {
            $this->msg("[FTP账户为空]".$ftp_url);
            return ;
        }
        if(strlen($pass) <1)
        {
            $this->msg("[FTP密码为空]".$ftp_url);
            return ;
        }
        if(strlen($cp_id) <1)
        {
            $this->msg("[cp ID为空]".$cp_id);
            return ;
        }
        $this->media_cp_id = $cp_id;
        $result_cp = $this->_get_cp_info($cp_id);
        if($result_cp['ret'] !=0)
        {
            $this->msg("[获取CP信息失败]".var_export($result_cp,true));
            return ;
        }
        if(!isset($this->arr_cp_config[$cp_id]) || empty($this->arr_cp_config[$cp_id]) || !is_array($this->arr_cp_config[$cp_id]))
        {
            $this->msg("[获取CP信息为空，数据库未配置]".$cp_id);
            return ;
        }
        $media_mode = (isset($this->arr_params['bk_queue_config']['nns_ext_info']['media_mode']) && strlen($this->arr_params['bk_queue_config']['nns_ext_info']['media_mode']) >0 && in_array($this->arr_params['bk_queue_config']['nns_ext_info']['media_mode'], array('0','1','2','3'))) ? $this->arr_params['bk_queue_config']['nns_ext_info']['media_mode'] : '1';
        $obj_ftp = new nl_ftp($host,$user,$pass,$port,300,true);
        $obj_ftp->ftp_list_file($path);
        $arr_file_list = $obj_ftp->get_arr_file_list();
        if(empty($arr_file_list) || !is_array($arr_file_list))
        {
            $this->msg("[获取ftp文件列表为空]".$cp_id);
            return ;
        }
        $temp_make_index_exsist = null;
        $arr_program_info = $arr_video_info = null;

        $arr_program_info_1 = $arr_video_info_1 = null;
        foreach ($arr_file_list as $key=>$last_file)
        {
            if($key == 0 && $cp_id != 'xiaole_mp3')
            {
                continue;
            }
            if($cp_id == 'xiaole_mp3')
            {
                $SystemLayer = 5;
                foreach ($last_file as $file_val)
                {
                    $file_val['bitrate'] = $bitrate;
                    $pathinfo = $this->my_path_info($file_val['url']);
                    $pathinfo['extension'] = strtolower($pathinfo['extension']);
                    if(!isset($pathinfo['extension']) || !in_array($pathinfo['extension'], array('mp3')))
                    {
                        continue;
                    }
                    if($key == 0)
                    {
                        $asset_info = $this->make_video_info($file_val,$pathinfo);
                        $arr_info = explode('/', $pathinfo['dirname']);
                        $cate_name = 'MP3';
                        $xml = $this->make_model($asset_info,$cate_name,$media_mode,$media_tag,$SystemLayer);
                        $this->insert_message($xml,$asset_info['video']['nns_name']);
                    }
                    else if($key == 1)
                    {
                        $arr_temp_info = explode('/', $pathinfo['dirname']);
                        $arr_temp_info = array_filter($arr_temp_info);
                        $video_name = array_pop($arr_temp_info);
                        $cate_name = "专辑";
                        $video_id = md5($video_name);

                        $index = ltrim(preg_replace('/\D/s', '', $pathinfo['filename']),'0');
                        if(strlen($index) <1 || $index > 450)
                        {
                            $this->msg("[获取多集信息列表分集有问题]".var_export($file_val,true));
                            continue;
                        }
                        $temp_make_index_exsist[$video_id][]=$index;
                        if(!isset($arr_video_info[$video_id]))
                        {
                            $arr_video_info[$video_id] = array(
                                'name'=>$video_name,
                                'id'=>$video_id,
                                'nns_count'=>$index,
                                'cate_name'=>$cate_name,
                                'repire_flag'=>true,
                                'asset_info'=>array(
                                    'video'=>array(
                                        'nns_id'=>$video_id,
                                        'nns_count'=>$index,
                                        'nns_cp_id'=>$cp_id,
                                        'nns_file_len'=>(45*60*60),
                                        'nns_name'=>$video_name,
                                    ),
                                )
                            );

                        }
                        else
                        {
                            if($index > $arr_video_info[$video_id]['asset_info']['video']['nns_count'])
                            {
                                $arr_video_info[$video_id]['asset_info']['video']['nns_count'] = $index;
                                $arr_video_info[$video_id]['nns_count'] = $index;
                            }
                        }
                        $arr_program_info[$video_id][] = array(
                            'file_val'=>$file_val,
                            'video_name'=>$video_name,
                            'filename'=>$pathinfo['filename'],
                            'video_id'=>$video_id,
                            'index'=>$index,
                            'cate_name'=>$cate_name,
                            'media_mode'=>$media_mode,
                            'media_tag'=>$media_tag,
                            'SystemLayer'=>$SystemLayer,
                        );
                    }
                }
                continue;
            }
            else
            {
                foreach ($last_file as $file_val)
                {
                    if(!isset($file_val['size']) || $file_val['size'] <100)
                    {
                        $this->msg("[文件大小<100不允许注入][文件路径：{$file_val['url']}]");
                    }
                    $file_val['placeholder']='placeholder';
                    $file_val['bitrate'] = $bitrate;
                    $pathinfo = $this->my_path_info($file_val['url']);
                    $pathinfo['extension'] = strtolower($pathinfo['extension']);
                    if(!isset($pathinfo['extension']) || !in_array($pathinfo['extension'], array('ts','mp4','mpg','mts')))
                    {
                        continue;
                    }
                    $SystemLayer = 1;
                    switch ($pathinfo['extension'])
                    {
                        case 'mp4':
                            $SystemLayer = 3;
                            break;
                        case 'mpg':
                            $SystemLayer = 4;
                            break;
                        case 'mts':
                            $SystemLayer = 6;
                            break;
                    }
                    if($cp_id == 'xiaole_encode')
                    {
                        if($key !=1)
                        {
                            continue;
                        }
                        $arr_temp_info = explode('/', $pathinfo['dirname']);
                        $arr_temp_info = array_filter($arr_temp_info);
                        $cate_name = array_pop($arr_temp_info);

                        $arr_cate_name = explode('-', $cate_name);
                        $arr_cate_name = array_filter($arr_cate_name);

                        if(count($arr_cate_name) >1)
                        {
                            $pathinfo['filename'] = array_pop($arr_cate_name).'-'.$pathinfo['filename'];
                        }
                        $cate_name = (isset($arr_cate_name[0]) && strlen($arr_cate_name[0]) >0) ? $arr_cate_name[0] : $cate_name;

                        $asset_info = $this->make_video_info($file_val,$pathinfo);
                        $xml = $this->make_model($asset_info,$cate_name,$media_mode,$media_tag,$SystemLayer);
                        $this->insert_message($xml,$asset_info['video']['nns_name']);
                        continue;
                    }

                    if($key == 1)
                    {
                        $file_val['len'] = $this->get_file_len($file_val['size']);
                        $asset_info = $this->make_video_info($file_val,$pathinfo);
                        $arr_info = explode('/', trim($pathinfo['dirname'],'/'));
                        $cate_name = array_pop($arr_info);
                        $xml = $this->make_model($asset_info,$cate_name,$media_mode,$media_tag,$SystemLayer);
                        $this->msg("[注入电影][栏目名称：{$cate_name}][电影名称：{$asset_info['video']['nns_name']}]");
                        $this->insert_message($xml,$cate_name.'|'.$asset_info['video']['nns_name']);
                    }
                    else if($key == 2)
                    {
                        $arr_temp_info = explode('/', $pathinfo['dirname']);
                        $arr_temp_info = array_filter($arr_temp_info);
                        $video_name = array_pop($arr_temp_info);

                        //修改内蒙导入使用，xinxin.deng 2018/5/24 10:45
                        $arr_asset = explode('_', $pathinfo['filename']);
                        //$video_name = $arr_asset[0];

                        $cate_name = array_pop($arr_temp_info);
                        $repire_flag = ($cate_name=='电视剧补集') ? true : false;
                        $video_id = md5($cate_name.'/'.$video_name);

                        $index = ltrim($arr_asset[1],'0');
                        //$index = ltrim(preg_replace('/\D/s', '', $pathinfo['filename']),'0');

                        if(strlen($index) <1 || $index > 150)
                        {
                            $temp_file_url = pathinfo($file_val['url']);
                            $this->msg("[获取多集信息列表分集有问题分集<1或者分集>150,不注入消息系统][路径:".$temp_file_url['dirname']."]");
                            continue;
                        }
                        $temp_make_index_exsist[$video_id][]=$index;

                        if(!isset($arr_video_info[$video_id]))
                        {
                            $arr_video_info[$video_id] = array(
                                'name'=>$cate_name.'|'.$video_name,
                                'id'=>$video_id,
                                'nns_count'=>$index,
                                'cate_name'=>$cate_name,
                                'repire_flag'=>$repire_flag,
                                'asset_info'=>array(
                                    'video'=>array(
                                        'nns_id'=>$video_id,
                                        'nns_count'=>$index,
                                        'nns_cp_id'=>$cp_id,
                                        'nns_file_len'=>$this->get_file_len($file_val['size'],'series'),
                                        'nns_name'=>$video_name,
                                    ),
                                )
                            );
                        }
                        else
                        {
                            if($index > $arr_video_info[$video_id]['asset_info']['video']['nns_count'])
                            {
                                $arr_video_info[$video_id]['asset_info']['video']['nns_count'] = $index;
                                $arr_video_info[$video_id]['nns_count'] = $index;
                            }
                        }
                        $file_val['len'] = $this->get_file_len($file_val['size'],'series');
                        $arr_program_info[$video_id][] = array(
                            'file_val'=>$file_val,
                            'video_name'=>$video_name . '第' . $index . '集',
                            'filename'=>$pathinfo['filename'],
                            'video_id'=>$video_id,
                            'index'=>$index,
                            'cate_name'=>$cate_name,
                            'media_mode'=>$media_mode,
                            'media_tag'=>$media_tag,
                            'SystemLayer'=>$SystemLayer,
                        );
                    }
                }
            }
        }

        if(!empty($arr_program_info) && is_array($arr_program_info))
        {
            foreach ($arr_program_info as $program_info_key=>$program_info_val)
            {
                if(empty($program_info_val) || !is_array($program_info_val))
                {
                    continue;
                }
                if(!isset($arr_video_info[$program_info_key]) || empty($arr_video_info[$program_info_key]) || !is_array($arr_video_info[$program_info_key]))
                {
                    $this->msg("[主媒资信息不存在不注入]");
                    continue;
                }
                $array_filter_temp_make_index_exsist = array_unique($temp_make_index_exsist[$program_info_key]);
                if(count($array_filter_temp_make_index_exsist) != count($temp_make_index_exsist[$program_info_key]))
                {
                    $last_exsist_val = $temp_exist_val = null;
                    foreach ($temp_make_index_exsist[$program_info_key] as $array_filter_val)
                    {
                        if(is_array($temp_exist_val) && !empty($temp_exist_val))
                        {
                            if(in_array($array_filter_val, $temp_exist_val))
                            {
                                $last_exsist_val[] = $array_filter_val;
                            }
                        }
                        $temp_exist_val[] = $array_filter_val;
                    }
                    if(is_array($temp_exist_val))
                    {
                        $temp_file_url = pathinfo($program_info_val[0]['file_val']['url']);
                        $this->msg("[分集信息存在多个同集数情况][路径:".$temp_file_url['dirname']."]多个为集数[".implode(",", $last_exsist_val)."]");
                    }
                    continue;
                }
                if($arr_video_info[$program_info_key]['repire_flag'] === true)
                {
                    $this->msg("----------------多集补集开始---------------------");
                }
                else
                {
                    $this->msg("----------------多集正常注入开始---------------------");
                    if(count($program_info_val) != $arr_video_info[$program_info_key]['asset_info']['video']['nns_count'])
                    {
                        $temp_all_index = range(1, $arr_video_info[$program_info_key]['asset_info']['video']['nns_count']);
                        foreach ($program_info_val as $program_info_value)
                        {
                            $temp_exsist_index[] = $program_info_value['index'];
                        }
                        $temp_last_index = array_diff($temp_all_index, $temp_exsist_index);
                        $temp_file_url = pathinfo($program_info_val[0]['file_val']['url']);
                        $this->msg("[分集信息不全，不注入消息系统][路径:".$temp_file_url['dirname']."]缺失集数[".implode(",", $temp_last_index)."]");
                        continue;
                    }
                }
                $this->msg("[----注入主媒资{$arr_video_info[$program_info_key]['name']}开始-----]");
                //注入主媒资
                $xml = $this->make_model_series($arr_video_info[$program_info_key]['asset_info'],$arr_video_info[$program_info_key]['cate_name'],$media_tag);
                $result = $this->insert_message($xml,$arr_video_info[$program_info_key]['name']);
                //注入分集
                $this->msg("[----注入分集开始-----]");
                foreach ($program_info_val as $program_info_value)
                {

                    $this->msg("[----注入分集({$program_info_value['index']})-----]");
                    $asset_info = $this->make_video_info_v3($program_info_value['file_val'],$program_info_value['video_name'],$program_info_value['filename'],$program_info_value['video_id'],$program_info_value['index']);
                    $xml = $this->make_model_program($asset_info,$program_info_value['cate_name'],$program_info_value['media_mode'],$program_info_value['media_tag'],$program_info_value['SystemLayer']);
                    $this->insert_message($xml,$program_info_value['cate_name'].'|'.$program_info_value['video_name'].'|'.$program_info_value['filename']);
                }
                if($arr_video_info[$program_info_key]['repire_flag'] === true)
                {
                    $this->msg("----------------多集补集结束---------------------");
                }
                else
                {
                    $this->msg("----------------多集正常注入结束---------------------");
                }
            }
        }
        return ;
    }

    /**
     * 获取文件时长
     * @param unknown $file_size
     * @param string $type
     * @return Ambigous <number, unknown>
     */
    public function get_file_len($file_size,$type='movie')
    {
        $result = floor((int)$file_size/500000);
        $result = $result > 0 ? $result : 0;
        if($type =='movie')
        {
            return $result> 0 ? $result : 2*60*60;
        }
        return $result> 0 ? $result : 40*60;
    }


    /**
     *
     * @param unknown $filepath
     */
    public function my_path_info($filepath)
    {
        $path_parts = array();
        $path_parts ['dirname'] = rtrim(substr($filepath, 0, strrpos($filepath, '/')),"/")."/";
        $path_parts ['basename'] = ltrim(substr($filepath, strrpos($filepath, '/')),"/");
        $path_parts ['extension'] = substr(strrchr($filepath, '.'), 1);
        $path_parts ['filename'] = ltrim(substr($path_parts ['basename'], 0, strrpos($path_parts ['basename'], '.')),"/");
        return $path_parts;
    }



    /**
     * 生成主媒资、分集、片源（针对电影）
     * @param unknown $asset_info
     * @param unknown $cate_name
     * @param unknown $media_mode
     * @param string $str_tag
     * @param number $SystemLayer
     */
    public function make_model($asset_info,$cate_name,$media_mode,$str_tag='26,',$SystemLayer=1)
    {
        $xml ='<?xml version="1.0" encoding="UTF-8"?>';
        $xml.=  '<ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
        $xml.=      '<Objects>';
        $xml.=          '<Object ElementType="Series" ContentID="'.$asset_info['video']['nns_id'].'" Action="REGIST" Code="'.$asset_info['video']['nns_id'].'">';
        $xml.=              '<Property Name="Name"><![CDATA['.$asset_info['video']['nns_name'].']]></Property>';
        $xml.=              '<Property Name="OrderNumber"/>';
        $xml.=              '<Property Name="OriginalName"/>';
        $xml.=              '<Property Name="AliasName"><![CDATA['.$asset_info['video']['nns_name'].']]></Property>';
        $xml.=              '<Property Name="EnglishName"/>';
        $xml.=              '<Property Name="SortName"/>';
        $xml.=              '<Property Name="SearchName"><![CDATA['.$asset_info['video']['nns_name'].']]></Property>';
        $xml.=              '<Property Name="OrgAirDate"><![CDATA[2012-05-05]]></Property>';
        $xml.=              '<Property Name="ReleaseYear"><![CDATA[2012-05-05]]></Property>';
        $xml.=              '<Property Name="LicensingWindowStart"/>';
        $xml.=              '<Property Name="LicensingWindowEnd"/>';
        $xml.=              '<Property Name="CPContentID"><![CDATA['.$asset_info['video']['nns_cp_id'].']]></Property>';
        $xml.=              '<Property Name="DisplayAsNew"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="DisplayAsLastChance"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="Macrovision"><![CDATA[1]]></Property>';
        $xml.=              '<Property Name="Price"/>';
        $xml.=              '<Property Name="VolumnCount"><![CDATA[1]]></Property>';
        $xml.=              '<Property Name="NewCount"><![CDATA[1]]></Property>';
        $xml.=              '<Property Name="Status"><![CDATA[1]]></Property>';
        $xml.=              '<Property Name="Description"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="ContentProvider"><![CDATA['.$asset_info['video']['nns_cp_id'].']]></Property>';
        $xml.=              '<Property Name="KeyWords"><![CDATA['.$asset_info['video']['nns_name'].']]></Property>';
        $xml.=              '<Property Name="OriginalCountry"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="ActorDisplay"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="WriterDisplay"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="Language"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="Kind"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="ViewType"><![CDATA[1]]></Property>';
        $xml.=              '<Property Name="Duration"><![CDATA['.$asset_info['video']['nns_file_len'].']]></Property>';
        $xml.=              '<Property Name="CategoryName"><![CDATA['.$cate_name.']]></Property>';
        $xml.=              '<Property Name="CategoryID"/>';
        $xml.=              '<Property Name="PlayCount"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="CategorySort"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="Tags"><![CDATA['.$str_tag.']]></Property>';
        $xml.=              '<Property Name="ViewPoint"/>';
        $xml.=              '<Property Name="StarLevel"><![CDATA[6]]></Property>';
        $xml.=              '<Property Name="Rating"/>';
        $xml.=              '<Property Name="Awards"/>';
        $xml.=              '<Property Name="Sort"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="Hotdegree"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="Reserve1"/>';
        $xml.=              '<Property Name="Reserve2"/>';
        $xml.=          '</Object>';
        $xml.=          '<Object ElementType="Program" ContentID="'.$asset_info['index']['nns_id'].'" Action="REGIST" Code="'.$asset_info['index']['nns_id'].'">';
        $xml.=              '<Property Name="Name"><![CDATA['.$asset_info['video']['nns_name'].']]></Property>';
        $xml.=              '<Property Name="CPContentID"><![CDATA['.$asset_info['video']['nns_cp_id'].']]></Property>';
        $xml.=              '<Property Name="OrderNumber"/>';
        $xml.=              '<Property Name="OriginalName"/>';
        $xml.=              '<Property Name="Sequence"/>';
        $xml.=              '<Property Name="SortName"/>';
        $xml.=              '<Property Name="SearchName"/>';
        $xml.=              '<Property Name="OriginalCountry"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="ActorDisplay"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="WriterDisplay"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="Language"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="OrgAirDate"><![CDATA[2012-05-05]]></Property>';
        $xml.=              '<Property Name="ReleaseYear"><![CDATA[2012-05-05]]></Property>';
        $xml.=              '<Property Name="LicensingWindowStart"/>';
        $xml.=              '<Property Name="LicensingWindowEnd"/>';
        $xml.=              '<Property Name="DisplayAsNew"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="DisplayAsLastChance"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="Macrovision"><![CDATA[1]]></Property>';
        $xml.=              '<Property Name="Description"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="PriceTaxIn"/>';
        $xml.=              '<Property Name="Status"><![CDATA[1]]></Property>';
        $xml.=              '<Property Name="SourceType"><![CDATA[1]]></Property>';
        $xml.=              '<Property Name="SeriesFlag"/>';
        $xml.=              '<Property Name="ContentProvider"><![CDATA['.$asset_info['video']['nns_cp_id'].']]></Property>';
        $xml.=              '<Property Name="KeyWords"><![CDATA['.$asset_info['video']['nns_name'].']]></Property>';
        $xml.=              '<Property Name="Tags"><![CDATA['.$str_tag.']]></Property>';
        $xml.=              '<Property Name="ViewPoint"/>';
        $xml.=              '<Property Name="StarLevel"><![CDATA[6]]></Property>';
        $xml.=              '<Property Name="Rating"/>';
        $xml.=              '<Property Name="Awards"/>';
        $xml.=              '<Property Name="Duration"><![CDATA['.$asset_info['video']['nns_file_len'].']]></Property>';
        $xml.=              '<Property Name="Hotdegree"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="Reserve1"/>';
        $xml.=              '<Property Name="Reserve2"/>';
        $xml.=              '<Property Name="Reserve3"/>';
        $xml.=              '<Property Name="Reserve4"/>';
        $xml.=              '<Property Name="Reserve5"/>';
        $xml.=          '</Object>';
        $xml.=          '<Object ElementType="Movie" ContentID="'.$asset_info['media']['nns_id'].'" Action="REGIST" Code="'.$asset_info['media']['nns_id'].'">';
        $xml.=              '<Property Name="Type"><![CDATA[1]]></Property>';
        $xml.=              '<Property Name="FileURL"><![CDATA['.$asset_info['media']['nns_url'].']]></Property>';
        $xml.=              '<Property Name="CPContentID"><![CDATA['.$asset_info['video']['nns_cp_id'].']]></Property>';
        $xml.=              '<Property Name="Name"><![CDATA['.$asset_info['video']['nns_name'].']]></Property>';
        $xml.=              '<Property Name="SourceDRMType"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="DestDRMType"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="AudioType"><![CDATA[1]]></Property>';
        $xml.=              '<Property Name="ScreenFormat"><![CDATA['.$asset_info['media']['nns_screenformat'].']]></Property>';
        $xml.=              '<Property Name="ClosedCaptioning"><![CDATA[1]]></Property>';
        $xml.=              '<Property Name="Tags"><![CDATA['.$str_tag.']]></Property>';
        $xml.=              '<Property Name="Duration"><![CDATA['.$asset_info['video']['nns_file_len'].']]></Property>';
        $xml.=              '<Property Name="FileSize"><![CDATA['.$asset_info['media']['nns_file_size'].']]></Property>';
        $xml.=              '<Property Name="BitRateType"><![CDATA['.$asset_info['media']['nns_bitrate'].']]></Property>';
        $xml.=              '<Property Name="VideoType"/>';
        $xml.=              '<Property Name="AudioEncodingType"><![CDATA[4]]></Property>';
        $xml.=              '<Property Name="Resolution"><![CDATA['.$asset_info['media']['nns_resolution'].']]></Property>';
        $xml.=              '<Property Name="MediaMode"><![CDATA['.$media_mode.']]></Property>';
        $xml.=              '<Property Name="SystemLayer"><![CDATA['.$SystemLayer.']]></Property>';
        $xml.=              '<Property Name="ServiceType"><![CDATA[HTTP]]></Property>';
        $xml.=              '<Property Name="Domain"/>';
        $xml.=              '<Property Name="Hotdegree"><![CDATA[0]]></Property>';
        $xml.=          '</Object>';
        $xml.=      '</Objects>';
        $xml.=      '<Mappings>';
        $xml.=          '<Mapping ParentType="Series" ParentID="'.$asset_info['video']['nns_id'].'" ElementType="Program" ElementID="'.$asset_info['index']['nns_id'].'" ParentCode="'.$asset_info['video']['nns_id'].'" ElementCode="'.$asset_info['index']['nns_id'].'" Action="REGIST"/>';
        $xml.=          '<Mapping ParentType="Program" ParentID="'.$asset_info['index']['nns_id'].'" ElementType="Movie" ElementID="'.$asset_info['media']['nns_id'].'" ParentCode="'.$asset_info['index']['nns_id'].'" ElementCode="'.$asset_info['media']['nns_id'].'" Action="REGIST"/>';
        $xml.=      '</Mappings>';
        $xml.=  '</ADI>';
        return $xml;
    }

    /**
     * 生成主媒资（针对电视剧）
     * @param unknown $asset_info
     * @param unknown $cate_name
     * @param string $str_tag
     */
    public function make_model_series($asset_info,$cate_name,$str_tag='26,')
    {
        $xml ='<?xml version="1.0" encoding="UTF-8"?>';
        $xml.=  '<ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
        $xml.=      '<Objects>';
        $xml.=          '<Object ElementType="Series" ContentID="'.$asset_info['video']['nns_id'].'" Action="REGIST" Code="'.$asset_info['video']['nns_id'].'">';
        $xml.=              '<Property Name="Name"><![CDATA['.$asset_info['video']['nns_name'].']]></Property>';
        $xml.=              '<Property Name="OrderNumber"/>';
        $xml.=              '<Property Name="OriginalName"/>';
        $xml.=              '<Property Name="AliasName"><![CDATA['.$asset_info['video']['nns_name'].']]></Property>';
        $xml.=              '<Property Name="EnglishName"/>';
        $xml.=              '<Property Name="SortName"/>';
        $xml.=              '<Property Name="SearchName"><![CDATA['.$asset_info['video']['nns_name'].']]></Property>';
        $xml.=              '<Property Name="OrgAirDate"><![CDATA[2012-05-05]]></Property>';
        $xml.=              '<Property Name="ReleaseYear"><![CDATA[2012-05-05]]></Property>';
        $xml.=              '<Property Name="LicensingWindowStart"/>';
        $xml.=              '<Property Name="LicensingWindowEnd"/>';
        $xml.=              '<Property Name="CPContentID"><![CDATA['.$asset_info['video']['nns_cp_id'].']]></Property>';
        $xml.=              '<Property Name="DisplayAsNew"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="DisplayAsLastChance"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="Macrovision"><![CDATA[1]]></Property>';
        $xml.=              '<Property Name="Price"/>';
        $xml.=              '<Property Name="VolumnCount"><![CDATA['.$asset_info['video']['nns_count'].']]></Property>';
        $xml.=              '<Property Name="NewCount"><![CDATA['.$asset_info['video']['nns_count'].']]></Property>';
        $xml.=              '<Property Name="Status"><![CDATA[1]]></Property>';
        $xml.=              '<Property Name="Description"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="ContentProvider"><![CDATA['.$asset_info['video']['nns_cp_id'].']]></Property>';
        $xml.=              '<Property Name="KeyWords"><![CDATA['.$asset_info['video']['nns_name'].']]></Property>';
        $xml.=              '<Property Name="OriginalCountry"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="ActorDisplay"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="WriterDisplay"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="Language"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="Kind"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="ViewType"><![CDATA[2]]></Property>';
        $xml.=              '<Property Name="Duration"><![CDATA['.$asset_info['video']['nns_file_len'].']]></Property>';
        $xml.=              '<Property Name="CategoryName"><![CDATA['.$cate_name.']]></Property>';
        $xml.=              '<Property Name="CategoryID"/>';
        $xml.=              '<Property Name="PlayCount"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="CategorySort"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="Tags"><![CDATA['.$str_tag.']]></Property>';
        $xml.=              '<Property Name="ViewPoint"/>';
        $xml.=              '<Property Name="StarLevel"><![CDATA[6]]></Property>';
        $xml.=              '<Property Name="Rating"/>';
        $xml.=              '<Property Name="Awards"/>';
        $xml.=              '<Property Name="Sort"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="Hotdegree"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="Reserve1"/>';
        $xml.=              '<Property Name="Reserve2"/>';
        $xml.=          '</Object>';
        $xml.=      '</Objects>';
        $xml.=  '</ADI>';
        return $xml;
    }

    /**
     * 生成分集、片源（针对电视剧）
     * @param unknown $asset_info
     * @param unknown $cate_name
     * @param unknown $media_mode
     * @param string $str_tag
     * @param number $SystemLayer
     */
    public function make_model_program($asset_info,$cate_name,$media_mode,$str_tag='26,',$SystemLayer=1)
    {
        $xml ='<?xml version="1.0" encoding="UTF-8"?>';
        $xml.=  '<ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
        $xml.=      '<Objects>';
        $xml.=          '<Object ElementType="Program" ContentID="'.$asset_info['index']['nns_id'].'" Action="REGIST" Code="'.$asset_info['index']['nns_id'].'">';
        $xml.=              '<Property Name="Name"><![CDATA['.$asset_info['index']['nns_name'].']]></Property>';
        $xml.=              '<Property Name="CPContentID"><![CDATA['.$asset_info['video']['nns_cp_id'].']]></Property>';
        $xml.=              '<Property Name="OrderNumber"/>';
        $xml.=              '<Property Name="OriginalName"/>';
        $xml.=              '<Property Name="Sequence">'.$asset_info['index']['nns_sequence'].'</Property>';
        $xml.=              '<Property Name="SortName"/>';
        $xml.=              '<Property Name="SearchName"/>';
        $xml.=              '<Property Name="OriginalCountry"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="ActorDisplay"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="WriterDisplay"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="Language"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="OrgAirDate"><![CDATA[2012-05-05]]></Property>';
        $xml.=              '<Property Name="ReleaseYear"><![CDATA[2012-05-05]]></Property>';
        $xml.=              '<Property Name="LicensingWindowStart"/>';
        $xml.=              '<Property Name="LicensingWindowEnd"/>';
        $xml.=              '<Property Name="DisplayAsNew"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="DisplayAsLastChance"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="Macrovision"><![CDATA[1]]></Property>';
        $xml.=              '<Property Name="Description"><![CDATA[]]></Property>';
        $xml.=              '<Property Name="PriceTaxIn"/>';
        $xml.=              '<Property Name="Status"><![CDATA[1]]></Property>';
        $xml.=              '<Property Name="SourceType"><![CDATA[1]]></Property>';
        $xml.=              '<Property Name="SeriesFlag"/>';
        $xml.=              '<Property Name="ContentProvider"><![CDATA['.$asset_info['video']['nns_cp_id'].']]></Property>';
        $xml.=              '<Property Name="KeyWords"><![CDATA['.$asset_info['video']['nns_name'].']]></Property>';
        $xml.=              '<Property Name="Tags"><![CDATA['.$str_tag.']]></Property>';
        $xml.=              '<Property Name="ViewPoint"/>';
        $xml.=              '<Property Name="StarLevel"><![CDATA[6]]></Property>';
        $xml.=              '<Property Name="Rating"/>';
        $xml.=              '<Property Name="Awards"/>';
        $xml.=              '<Property Name="Duration"><![CDATA['.$asset_info['video']['nns_file_len'].']]></Property>';
        $xml.=              '<Property Name="Hotdegree"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="Reserve1"/>';
        $xml.=              '<Property Name="Reserve2"/>';
        $xml.=              '<Property Name="Reserve3"/>';
        $xml.=              '<Property Name="Reserve4"/>';
        $xml.=              '<Property Name="Reserve5"/>';
        $xml.=          '</Object>';
        $xml.=          '<Object ElementType="Movie" ContentID="'.$asset_info['media']['nns_id'].'" Action="REGIST" Code="'.$asset_info['media']['nns_id'].'">';
        $xml.=              '<Property Name="Type"><![CDATA[1]]></Property>';
        $xml.=              '<Property Name="FileURL"><![CDATA['.$asset_info['media']['nns_url'].']]></Property>';
        $xml.=              '<Property Name="CPContentID"><![CDATA['.$asset_info['video']['nns_cp_id'].']]></Property>';
        $xml.=              '<Property Name="Name"><![CDATA['.$asset_info['index']['nns_name'].']]></Property>';
        $xml.=              '<Property Name="SourceDRMType"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="DestDRMType"><![CDATA[0]]></Property>';
        $xml.=              '<Property Name="AudioType"><![CDATA[1]]></Property>';
        $xml.=              '<Property Name="ScreenFormat"><![CDATA['.$asset_info['media']['nns_screenformat'].']]></Property>';
        $xml.=              '<Property Name="ClosedCaptioning"><![CDATA[1]]></Property>';
        $xml.=              '<Property Name="Tags"><![CDATA['.$str_tag.']]></Property>';
        $xml.=              '<Property Name="Duration"><![CDATA['.$asset_info['video']['nns_file_len'].']]></Property>';
        $xml.=              '<Property Name="FileSize"><![CDATA['.$asset_info['media']['nns_file_size'].']]></Property>';
        $xml.=              '<Property Name="BitRateType"><![CDATA['.$asset_info['media']['nns_bitrate'].']]></Property>';
        $xml.=              '<Property Name="VideoType"/>';
        $xml.=              '<Property Name="AudioEncodingType"><![CDATA[4]]></Property>';
        $xml.=              '<Property Name="Resolution"><![CDATA['.$asset_info['media']['nns_resolution'].']]></Property>';
        $xml.=              '<Property Name="MediaMode"><![CDATA['.$media_mode.']]></Property>';
        $xml.=              '<Property Name="SystemLayer"><![CDATA['.$SystemLayer.']]></Property>';
        $xml.=              '<Property Name="ServiceType"><![CDATA[HTTP]]></Property>';
        $xml.=              '<Property Name="Domain"/>';
        $xml.=              '<Property Name="Hotdegree"><![CDATA[0]]></Property>';
        $xml.=          '</Object>';
        $xml.=      '</Objects>';
        $xml.=      '<Mappings>';
        $xml.=          '<Mapping ParentType="Series" ParentID="'.$asset_info['video']['nns_id'].'" ElementType="Program" ElementID="'.$asset_info['index']['nns_id'].'" ParentCode="'.$asset_info['video']['nns_id'].'" ElementCode="'.$asset_info['index']['nns_id'].'" Action="REGIST"/>';
        $xml.=          '<Mapping ParentType="Program" ParentID="'.$asset_info['index']['nns_id'].'" ElementType="Movie" ElementID="'.$asset_info['media']['nns_id'].'" ParentCode="'.$asset_info['index']['nns_id'].'" ElementCode="'.$asset_info['media']['nns_id'].'" Action="REGIST"/>';
        $xml.=      '</Mappings>';
        $xml.=  '</ADI>';
        return $xml;
    }

    public function make_video_info($arr,$pathinfo)
    {
        $asset_info = array();
        $asset_info['video']['nns_name'] =$pathinfo['filename'];
        $asset_info['video']['nns_id'] = $this->gkey('video',$arr);
        $asset_info['video']['nns_cp_id'] = $this->media_cp_id;
        $asset_info['video']['nns_file_len'] = $arr['len'];
        $asset_info['index']['nns_id'] = $this->gkey('index',$arr);
        $asset_info['media']['nns_id'] = $this->gkey('media',$arr);

        $asset_info['media']['nns_url'] = $arr['url'];
        $asset_info['media']['nns_screenformat'] = isset($arr['screenformat']) ? $arr['screenformat'] : '16x9';
        $asset_info['media']['nns_file_size'] = $arr['size'];
        $asset_info['media']['nns_bitrate'] = isset($arr['bitrate']) ? $arr['bitrate'] : '8008';
        $asset_info['media']['nns_resolution'] = isset($arr['resolution']) ? $arr['resolution'] : '1920*1080';
        return $asset_info;
    }

    public function make_video_info_v3($arr,$video_name,$index_name,$video_id,$index)
    {
        $asset_info = array();
        $asset_info['video']['nns_name'] =$video_name;
        $asset_info['video']['nns_id'] = $video_id;
        $asset_info['video']['nns_cp_id'] = $this->media_cp_id;
        $asset_info['video']['nns_file_len'] = $arr['len'];

        $asset_info['index']['nns_name'] =$index_name;
        $asset_info['index']['nns_id'] = $this->gkey('index',$arr);
        $asset_info['index']['nns_sequence'] = $index;
        $asset_info['media']['nns_id'] = $this->gkey('media',$arr);

        $asset_info['media']['nns_url'] = $arr['url'];
        $asset_info['media']['nns_screenformat'] = isset($arr['screenformat']) ? $arr['screenformat'] : '16x9';
        $asset_info['media']['nns_file_size'] = $arr['size'];
        $asset_info['media']['nns_bitrate'] = isset($arr['bitrate']) ? $arr['bitrate'] : '8008';
        $asset_info['media']['nns_resolution'] = isset($arr['resolution']) ? $arr['resolution'] : '1920*1080';
        return $asset_info;
    }

    public function make_video_info_v2($arr,$url)
    {
        $arr_file = explode('\\', $arr['ClipMeta']['filename']);
        $asset_info = array();
        $asset_info['video']['nns_name'] =$arr['ClipInfo']['Name'];
        $asset_info['video']['nns_id'] = $this->gkey('video',$arr);
        $asset_info['video']['nns_cp_id'] = $this->media_cp_id;
        $asset_info['video']['nns_file_len'] = $arr['ClipMeta']['size'];
        $asset_info['index']['nns_id'] = $this->gkey('index',$arr);
        $asset_info['media']['nns_id'] = $this->gkey('media',$arr);
        $asset_info['media']['nns_url'] = $url.array_pop($arr_file);
        $asset_info['media']['nns_screenformat'] = isset($arr['ClipMeta']['AspectRatio']) ? str_replace(':', 'x', $arr['ClipMeta']['AspectRatio']) : '16x9';
        $asset_info['media']['nns_file_size'] = $arr['ClipMeta']['size'];
        $asset_info['media']['nns_bitrate'] = isset($arr['ClipInfo']['TotalBitRate']) ? $arr['ClipInfo']['TotalBitRate'] : '8008';
        $asset_info['media']['nns_resolution'] = (isset($arr['ClipMeta']['resolutionwidth']) && isset($arr['ClipMeta']['resolutionheigth'])) ? $arr['ClipMeta']['resolutionwidth'].'*'.$arr['ClipMeta']['resolutionheigth'] : '1920*1080';
        return $asset_info;
    }


    /**
     * 获取注入ID
     * @param unknown $mainkey
     * @param string $params
     */
    public function gkey ($mainkey, $params = null)
    {
        $gkey = $mainkey;
        foreach ($params as $pkey => $pvalue)
        {
            $gkey .= '|#' . $pvalue;
        }
        return MD5($gkey);
    }

    /**
     * 注入消息队列
     * @param unknown $dc
     * @param unknown $xml
     * @param unknown $name
     */
    public function insert_message($xml,$name)
    {
        $message_data = array ();
        //读取毫秒级时间
        list ($usec, $sec) = explode(' ', microtime());
        $time = str_pad(intval(substr($usec, 2, 4)), 4, '0', STR_PAD_LEFT);
        $message_data['nns_id'] = np_guid_rand();
        $message_data['nns_message_time'] = date('YmdHis', time()) . $time;
        $message_data['nns_message_id'] = md5($xml);
        $message_data['nns_message_xml'] = '';
        $message_data['nns_message_state'] = '0';
        $message_data['nns_message_content'] = $xml;
        $message_data['nns_create_time'] = date('Y-m-d H:i:s', time());
        $message_data['nns_again'] = 0;
        $message_data['nns_delete'] = 0;
        $message_data['nns_cp_id'] = $this->media_cp_id;
        //操作
        $message_data['nns_action'] = '1';
        $message_data['nns_type'] = '1';
        $message_data['nns_name'] = $name;
        $result = nl_message::query_message_by_message_id($this->obj_dc, $message_data['nns_message_id'], $this->media_cp_id);
        if(isset($result['data_info']) && is_array($result['data_info']) && !empty($result['data_info']))
        {
            $this->msg("[内容已存在不再注入][消息名称：{$name}]");
            return $result;
        }
        $result = nl_message::query_message_by_message_name($this->obj_dc, $name, $this->media_cp_id);
        if(isset($result['data_info']) && is_array($result['data_info']) && !empty($result['data_info']))
        {
            $this->msg("[名称重复不再注入][消息名称：{$name}]");
            return $result;
        }
        return nl_message::add($this->obj_dc, $message_data);
    }
}
$arr_files = pathinfo(__FILE__);
$file_name = $arr_files['filename'];
$timer_execute = new timer_execute($file_name, $file_name,__FILE__,'ftp_media_to_db_nmxl');
$timer_execute->run();